<template>
  <div class="page-wrap">
    <div class="header">
      <div class="title">小票与标签模板</div>
      <el-radio-group v-model="currentType" @change="onTypeChange">
        <el-radio-button label="receipt">小票模板</el-radio-button>
        <el-radio-button label="label">价格标签</el-radio-button>
      </el-radio-group>
      <div class="spacer" />
      <el-button type="primary" @click="createNew(currentType)">新增{{ currentType==='receipt' ? '小票模板' : '价格标签' }}</el-button>
    </div>

    <div class="layout">
      <aside class="side">
        <el-card shadow="never" class="full">
          <template #header>
            <div class="side-header">
              <span>模板列表</span>
            </div>
          </template>

          <el-table :data="list" height="100%" size="small" @row-click="row => selectedId = row.id" :row-class-name="({row}) => row.id===selectedId ? 'is-active' : ''">
            <el-table-column type="index" width="50" label="#" />
            <el-table-column label="名称" min-width="140">
              <template #default="{ row }">
                <div class="name-line">
                  <span class="name">{{ row.name }}</span>
                  <el-tag v-if="row.isDefault" size="small" type="success">默认</el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="210" fixed="right">
              <template #default="{ row }">
                <el-button size="small" @click.stop="selectedId=row.id">编辑</el-button>
                <el-button size="small" @click.stop="onClone(row)">克隆</el-button>
                <el-button size="small" @click.stop="onSetDefault(row)" :disabled="row.isDefault">设为默认</el-button>
                <el-button size="small" type="danger" @click.stop="onRemove(row)" :disabled="row.isDefault">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </aside>

      <section class="editor">
        <el-card shadow="never" class="full">
          <template #header>
            <div class="editor-header actions-row">
              <span>模板编辑</span>
              <div class="spacer" />
              <div class="actions">
                <el-button @click="onResetContent">重置示例</el-button>
                <el-button type="primary" @click="onSave" :disabled="!selected">保存</el-button>
              </div>
            </div>
          </template>

          <template v-if="selected">
            <el-form :model="edit" label-width="110px" class="form">
              <el-form-item label="模板名称">
                <el-input v-model="edit.name" placeholder="请输入模板名称" />
              </el-form-item>

              <template v-if="currentType==='receipt'">
                <el-form-item label="票宽(mm)">
                  <el-input-number v-model="edit.widthMm" :min="40" :max="120" />
                </el-form-item>
                <el-form-item label="字体大小(px)">
                  <el-input-number v-model="edit.fontSize" :min="8" :max="24" />
                </el-form-item>
                <el-form-item label="行高">
                  <el-input-number v-model="edit.lineHeight" :step="0.1" :min="1" :max="2" />
                </el-form-item>
              </template>

              <template v-else>
                <el-form-item label="标签宽(mm)">
                  <el-input-number v-model="edit.labelWidthMm" :min="10" :max="120" />
                </el-form-item>
                <el-form-item label="标签高(mm)">
                  <el-input-number v-model="edit.labelHeightMm" :min="10" :max="120" />
                </el-form-item>
                <el-form-item label="列数">
                  <el-input-number v-model="edit.columns" :min="1" :max="6" />
                </el-form-item>
                <el-form-item label="行距(mm)">
                  <el-input-number v-model="edit.gapMm" :min="0" :max="10" />
                </el-form-item>
                <el-form-item label="字体大小(px)">
                  <el-input-number v-model="edit.fontSize" :min="10" :max="32" />
                </el-form-item>
              </template>

              <el-form-item label="模板内容">
                <el-input v-model="edit.content" type="textarea" :rows="currentType==='receipt' ? 16 : 12" placeholder="可使用 {{xxx}} 占位符；循环使用 {{#each path}}...{{/each}}" />
              </el-form-item>

              <el-alert type="info" show-icon :closable="false" class="hint">
                <template #title>
                  <div>
                    支持占位符：
                    <span v-if="currentType==='receipt'">
                      <code v-pre>{{store.name}}</code>、
                      <code v-pre>{{cashier.name}}</code>、
                      <code v-pre>{{order.sn}}</code>、
                      <code v-pre>{{order.total}}</code>、
                      <code v-pre>{{#each order.items}}...{{/each}}</code>
                    </span>
                    <span v-else>
                      <code v-pre>{{product.name}}</code>、
                      <code v-pre>{{product.price}}</code>、
                      <code v-pre>{{product.code}}</code>
                    </span>
                  </div>
                </template>
              </el-alert>
            </el-form>
          </template>

          <template v-else>
            <el-empty description="请选择或新增一个模板" />
          </template>
        </el-card>
      </section>

      <aside class="preview">
        <el-card shadow="never" class="full">
          <template #header>
            <div class="editor-header actions-row">
              <span>效果预览</span>
              <div class="spacer" />
              <div class="actions">
                <el-button @click="onPrint" :disabled="!selected">打印预览</el-button>
              </div>
            </div>
          </template>

          <div v-if="currentType==='receipt'" class="preview-receipt">
            <div class="paper" :style="{ width: previewReceipt.widthPx + 'px', fontSize: previewReceipt.fontSize + 'px', lineHeight: previewReceipt.lineHeight }">
              <div class="inner" v-html="previewReceipt.html"></div>
            </div>
          </div>
          <div v-else class="preview-label">
            <div class="label-grid" :style="previewLabel.gridCss" v-html="previewLabel.html"></div>
          </div>
        </el-card>
      </aside>
    </div>
  </div>
  
</template>

<script setup>
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useReceiptStore } from '@/stores/receipt.js'

const store = useReceiptStore()

const currentType = ref('receipt')
const selectedId = ref('')
const edit = reactive({ id: '', type: 'receipt', name: '', content: '' })

const list = computed(() => currentType.value === 'receipt' ? store.receiptTemplates : store.labelTemplates)
const selected = computed(() => store.getTemplateById(selectedId.value))

const previewReceipt = computed(() => {
  if (!selected.value || currentType.value !== 'receipt') return { html: '', widthPx: 260, fontSize: 12, lineHeight: 1.4 }
  return store.renderReceiptHtml(edit)
})

const sampleProducts = computed(() => store.getSampleLabelProducts())
const previewLabel = computed(() => {
  if (!selected.value || currentType.value !== 'label') return { html: '', gridCss: '', labelCss: '' }
  return store.renderLabelGridHtml(edit, sampleProducts.value)
})

function labelSingleHtml(p){
  // 使用 store 的渲染逻辑，为单条商品生成 HTML
  const tmp = store.renderLabelGridHtml(edit, [p])
  return tmp.html
}

function ensureSelection() {
  const arr = list.value
  if (arr.length) {
    if (!arr.find(x => x.id === selectedId.value)) {
      selectedId.value = arr[0].id
    }
  } else {
    selectedId.value = ''
  }
}

function syncEditFromSelected(){
  const t = selected.value
  if (!t) return
  Object.assign(edit, JSON.parse(JSON.stringify(t)))
}

function onTypeChange(){
  ensureSelection()
  syncEditFromSelected()
}

function createNew(type){
  const tpl = store.addTemplate({ type, name: type==='receipt' ? '新小票模板' : '新价格标签', content: '' })
  selectedId.value = tpl.id
  syncEditFromSelected()
  ElMessage.success('已创建模板')
}

function onClone(row){
  const copy = store.cloneTemplate(row.id)
  if (copy) {
    selectedId.value = copy.id
    syncEditFromSelected()
    ElMessage.success('已克隆为副本')
  }
}

function onRemove(row){
  ElMessageBox.confirm('删除后不可恢复，确定删除该模板？', '提示', { type: 'warning' })
    .then(() => {
      const ok = store.removeTemplate(row.id)
      if (ok) {
        ensureSelection()
        syncEditFromSelected()
        ElMessage.success('已删除')
      }
    })
    .catch(()=>{})
}

function onSetDefault(row){
  store.setDefault(row.id)
  ElMessage.success('已设为默认')
}

function onResetContent(){
  if (!selected.value) return
  if (currentType.value === 'receipt') {
    const def = store.renderReceiptHtml().html
    // 还原为默认模板内容（从默认模板取，而不是预览结果）
    const defTpl = store.receiptTemplates.find(t => t.isDefault)
    if (defTpl) edit.content = defTpl.content
  } else {
    const defTpl = store.labelTemplates.find(t => t.isDefault)
    if (defTpl) edit.content = defTpl.content
  }
}

function onSave(){
  if (!selected.value) return
  const merged = store.updateTemplate(selected.value.id, { ...edit })
  if (merged) {
    ElMessage.success('已保存')
  }
}

function onPrint(){
  if (!selected.value) return
  if (currentType.value === 'receipt') {
    const r = store.renderReceiptHtml(edit)
    store.openPrintWindow(`<div>${r.html}</div>`, { widthPx: r.widthPx, fontSize: r.fontSize, lineHeight: r.lineHeight })
  } else {
    const r = store.renderLabelGridHtml(edit, sampleProducts.value)
    const inner = `<div class="label-grid" style="${r.gridCss}">${r.html}</div>`
    store.openPrintWindow(inner, { widthPx: 600, fontSize: edit.fontSize || 14, lineHeight: 1.2 })
  }
}

onMounted(() => {
  store.initialize()
  ensureSelection()
  syncEditFromSelected()
})

watch(selectedId, () => { syncEditFromSelected() })
watch(currentType, () => { ensureSelection(); syncEditFromSelected() })
</script>

<style scoped>
.page-wrap { padding: 16px; }
.header { display: flex; align-items: center; gap: 12px; margin-bottom: 12px; }
.title { font-size: 18px; font-weight: 700; }
.spacer { flex: 1; }
.layout { display: grid; grid-template-columns: 360px 1fr 420px; gap: 12px; }
.side, .editor, .preview { height: calc(100vh - 140px); }
.full { height: 100%; display: flex; flex-direction: column; }
.side :deep(.el-card__body) { flex: 1; display: flex; flex-direction: column; padding: 0; }
.preview :deep(.el-card__body) { height: 100%; overflow: auto; }
.editor :deep(.el-card__body) { overflow: auto; }
.actions-row { display: flex; align-items: center; gap: 8px; }
.actions { display: inline-flex; gap: 8px; align-items: center; flex-wrap: nowrap; }
@media (max-width: 640px) {
  .actions { flex-wrap: wrap; }
}
.side-header { display: flex; align-items: center; justify-content: space-between; }
.name-line { display: flex; align-items: center; gap: 6px; }
.name { max-width: 160px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.form { padding-right: 8px; }
.hint { margin-top: -6px; }

.preview-receipt { display: flex; justify-content: center; padding: 8px; }
.paper { background: #fff; padding: 8px 10px; box-shadow: 0 1px 3px rgba(0,0,0,.08); border-radius: 6px; }
.inner { white-space: normal; word-break: break-all; }

.preview-label { padding: 8px; }
.label-grid { background: #fff; padding: 8px; box-shadow: 0 1px 3px rgba(0,0,0,.08); border-radius: 6px; }
.label-item { background: #fff; border: 1px dashed #e5e7eb; display: flex; align-items: center; justify-content: center; text-align: center; padding: 4px; }

@media (max-width: 1360px) {
  .layout { grid-template-columns: 320px 1fr 360px; }
}
@media (max-width: 1200px) {
  .layout { grid-template-columns: 1fr; }
  .side, .preview { height: auto; }
}
</style>


